package com.zy.find;

import com.google.common.collect.Lists;

import java.util.List;

/**
 * __|__ __|__
 * _|_   _|_
 * .---. .---.
 * |___| |___|
 * _\_/_ _\_/_
 * _X_   _X_
 * |   | |   |
 * |___| |___|
 *
 * @Author zhaoyi
 * @date 2020/4/10
 *  * <p>
 *  * https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/8/sorting-and-searching/53/
 *  * 二分查找变体 -- 第一个错误版本
 */
public class FirstError {

    public static void main(String[] args) {
        //int i = firstBadVersion(5);
        int i = firstBadVersionV2(5);
        System.out.println(i);
    }


    public static int firstBadVersionV2(int n) {
        int left = 1;
        int right = n;
        while (left < right) {
            //防止 a+b 超过int范围
            int mid = left + ((right - left) >> 1);
            if (isBadVersion(mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }


    public static int firstBadVersion(int n) {
        if (!isBadVersion(n)) {
            return -1;
        }
        return find(1, n);
    }

    private static int find(int left, int right) {

        if (left >= right) {
            return left;
        }

        int mid = left + ((right - left) >> 1);
        if (!isBadVersion(mid)) {
            return find(mid + 1, right);
        } else if (isBadVersion(mid) && mid == 1) {
            return mid;
        } else if (isBadVersion(mid) && !isBadVersion(mid - 1)) {
            return mid;
        } else {
            return find(left, mid - 1);
        }
    }

    //模拟错误版本
    private static boolean isBadVersion(int i) {
        List<Boolean> flags = Lists.newArrayList(false, false, false, true, true);
        //List<Boolean> flags = Lists.newArrayList(false, true);
        return flags.get(i - 1);
    }


}
